package com.mycompany.repository.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.mycompany.entity.Mom;
import com.mycompany.repository.MomDao;
import com.mycompany.unity.DateUnity;

@Repository
public class MomDaoImpl implements MomDao {
	
	private EntityManager em;
	String sqlQuery="";
	

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.em = entityManager;
	}

	public void persist(Mom mom) {
			em.persist(mom);
	}

	public void merge(Mom mom) {
		em.merge(mom);
	}

	@Override
	public void remove(Mom mom) {
		em.remove(em.merge(mom));
	}

	@Override
	public Mom getMom(Integer momId) {
		sqlQuery = "select m from Mom m where m.id= :id";
		return (Mom) em.createQuery(sqlQuery).setParameter("id", momId).getSingleResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Mom> getAllMom() { 
		sqlQuery = "select m from Mom m ORDER BY id DESC LIMIT 0,30";
        return em.createQuery(sqlQuery).getResultList();
	}
	
	

    @Override
    public Mom getMom(Mom mom)
    {
        sqlQuery = "select m from Mom m where m.id= :id";
        return (Mom) em.createQuery(sqlQuery).setParameter("id", mom.getId()).getSingleResult();
    }	

    
    @SuppressWarnings("unchecked")
	@Override
    public List<Mom> getAllMomRound() { 
         Date startDate = DateUnity.beforeOfDay(-14);
		 Date endDate = DateUnity.afterOfDay(2);
	     DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	    sqlQuery = "select m from Mom m where to_date BETWEEN '"+df.format(startDate)+"' AND '"+df.format(endDate)+"' ORDER BY id DESC ";
        return em.createQuery(sqlQuery).getResultList();
    }
    
    @Override
    public String getTotlePriceRound()
    {    
    	Date startDate = DateUnity.beforeOfDay(-14);
    	Date endDate = DateUnity.afterOfDay(2);
    	DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        sqlQuery = "select sum(m.price) as totle from Mom m where to_date BETWEEN '"+df.format(startDate)+"' AND '"+df.format(endDate)+"' ORDER BY id DESC ";
        return  em.createQuery(sqlQuery).getSingleResult().toString();
    }
   
}
